package com.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @author XiaoHao
 * @date 2021-03-18 09:55
 * 数据库配置类
 */
@Configuration
public class DataSourceConfig {
    @Bean(name="db")
    @ConfigurationProperties(prefix = "spring.datasource.db")
    public DataSource dataSource1(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name="mysql")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource dataSource2(){
        return DataSourceBuilder.create().build();
    }
    @Primary
    @Bean(name="dynamicDS1")
    public DataSource dataSource(){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dataSource1());
        //配置多数据源
        HashMap<Object, Object> dsMap = new HashMap<>();
        dsMap.put("db",dataSource1());
        dsMap.put("mysql",dataSource2());

        dynamicDataSource.setTargetDataSources(dsMap);
        return dynamicDataSource;
    }

    /**
     * 配置@Transactional注解事务
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dataSource());
    }
}
